package model

import (
	"errors"
	"gorm.io/gorm"
	"vueBasic/app/admin/filter"
	"vueBasic/extend/conv"
	"vueBasic/global"
)

var AdminUserM = new(AdminUser)

type AdminUser struct {
	Id            uint       `form:"id" json:"id"`
	Username      string     `form:"username" json:"username"`
	Password      string     `form:"password" json:"-"`
	Nickname      string     `form:"nickname" json:"nickname"`
	Mobile        string     `form:"mobile" json:"mobile"`
	Email         string     `form:"email" json:"email"`
	Qq            string     `form:"qq" json:"qq"`
	Status        int        `form:"status" json:"status"`
	RoleId        int        `form:"role_id" json:"role_id"`
	LastLoginIp   string     `form:"last_login_ip" json:"last_login_ip"`
	LastLoginTime int64      `form:"last_login_time" json:"last_login_time"`
	AddTime       int64      `form:"add_time" json:"add_time"`
	UpdateTime    int64      `form:"update_time" json:"update_time"`
	IsSuper       int        `form:"-" json:"-"`
	Role          *roleModel `json:"role" grom:"foreignKey:RoleId,references:Id"` //关联模型
}

func (*AdminUser) TableName() string {
	return global.CONF.Database.Db.Prefix + "admin_user"
}

func (*AdminUser) GetAdminUserInfoByUsername(username string) (*AdminUser, error) {
	var user AdminUser
	err := global.DB.Model(&AdminUser{}).Where("username=?", username).Limit(1).First(&user).Error
	if err != nil {
		if errors.Is(err, gorm.ErrRecordNotFound) {
			return nil, errors.New("账号不存在！")
		} else {
			return nil, err
		}
	}
	return &user, nil
}

func (*AdminUser) GetList(req *filter.AdminAdminuserReq) ([]*AdminUser, int64, error) {
	var (
		list  []*AdminUser
		count int64
	)
	query := global.DB.Model(&AdminUser{})
	if !conv.IsEmpty(req.Username) {
		query = query.Where("username=?", req.Username)
	}
	if !conv.IsEmpty(req.Nickname) {
		query = query.Where("nickname=?", req.Nickname)
	}
	if !conv.IsEmpty(req.Mobile) {
		query = query.Where("mobile=?", req.Mobile)
	}
	if !conv.IsEmpty(req.RoleId) {
		query = query.Where("role_id=?", req.RoleId)
	}
	if !conv.IsEmpty(req.Status) {
		query = query.Where("status=?", req.Status)
	}
	query = query.Preload("Role", func(db *gorm.DB) *gorm.DB {
		return db.Select("id,title")
	})
	if err := query.Limit(req.Limit).Offset((req.Page - 1) * req.Limit).Find(&list).Error; err != nil {
		return nil, 0, err
	}
	query.Count(&count)
	return list, count, nil
}

func (*AdminUser) Add(req *filter.AdminAdminuserAddReq) (uint, error) {
	entity := &AdminUser{}
	entity.Username = req.Username
	entity.Nickname = req.Nickname
	entity.Password = conv.EncryptPassword(req.Password)
	entity.RoleId = req.RoleId
	entity.Mobile = req.Mobile
	entity.Email = req.Email
	entity.Qq = req.Qq
	entity.Status = req.Status
	entity.AddTime = conv.NowUnix()
	entity.LastLoginIp = ""
	entity.UpdateTime = conv.NowUnix()
	//判断是不是超管
	if req.RoleId == 9 {
		entity.IsSuper = 1
	}
	if err := global.DB.Create(entity).Error; err != nil {
		return 0, err
	}
	return entity.Id, nil

}

func (*AdminUser) GetAdminByUsername(username string) (*AdminUser, error) {
	var info AdminUser
	if err := global.DB.Where("username=?", username).Limit(1).First(&AdminUser{}).Error; err != nil {
		return nil, err
	}
	return &info, nil
}

func (*AdminUser) GetAdminById(req *filter.AdminAdminuserGetUpdateInfoReq) (*AdminUser, error) {
	entity := AdminUser{}
	if err := global.DB.Preload("Role").Where("id=?", req.Id).Limit(1).First(&entity).Error; err != nil {
		return nil, err
	}
	return &entity, nil
}

func (*AdminUser) Update(req *filter.AdminAdminuserUpdateReq) (uint, error) {
	entity := AdminUser{Id: req.Id}
	global.DB.First(&entity)
	entity.Username = req.Username
	entity.Nickname = req.Nickname
	if !conv.IsEmpty(req.Password) {
		entity.Password = conv.EncryptPassword(req.Password)
	}
	entity.RoleId = req.RoleId
	entity.Mobile = req.Mobile
	entity.Email = req.Email
	entity.Qq = req.Qq
	entity.Status = req.Status
	entity.LastLoginIp = ""
	entity.UpdateTime = conv.NowUnix()
	//判断是不是超管
	if req.RoleId == 9 {
		entity.IsSuper = 1
	}
	if err := global.DB.Save(entity).Error; err != nil {
		return 0, err
	}
	return entity.Id, nil

}

// 删除
func (*AdminUser) Delete(ids []string) (uint, error) {
	query := global.DB.Where("id IN ?", ids)
	err := query.Delete(&AdminUser{}).Error
	if err != nil {
		return 0, err
	}
	return 1, nil
}

func (*AdminUser) ResetPwd(req *filter.AdminAdminuserResetPwdReq) error {
	entity := AdminUser{
		Id: conv.Uint(req.Id),
	}
	if err := global.DB.Limit(1).First(&entity).Error; err != nil {
		return err
	}
	if err := global.DB.Model(&entity).Update("password", conv.EncryptPassword(req.Pwd)).Error; err != nil {
		return err
	}
	return nil
}

func (*AdminUser) UpdateExt(req map[string]interface{}) error {
	query := global.DB.Model(&AdminUser{})
	if err := query.Where("id=?", req["id"]).Updates(req).Error; err != nil {
		return err
	}
	return nil
}
